package tech.aichan.AiQA.utils;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.ChatMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.zhipuai.ZhipuAiChatClient;
import org.springframework.ai.zhipuai.ZhipuAiChatOptions;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author mengyu
 * @date 2024/05/23 14:41
 */
@Component
public class AiUtils {

    private final Float UNSTABLE_TEMPERATURE = 0.05F;
    private final Float STABLE_TEMPERATURE = 0.99F;

    @Resource
    private ZhipuAiChatClient chatClient;

    /**
     * 发送请求
     * @param chatMessages 向Ai发送的语句
     * @param temperature 随机度（值越大Ai生成的结果随机性越高）
     * @return Ai生成的结果
     */
    public String doRequest(List<Message> chatMessages, Float temperature){
        ChatResponse call = chatClient.call(
                new Prompt(
                        chatMessages,
                        ZhipuAiChatOptions
                                .builder()
                                .withTemperature(temperature)
                                .build()
                )
        );
        return call.getResult().getOutput().getContent();
    }

    /**
     * 使用字符串发送请求
     * @param promptStr 提示语
     * @param userStr  生成语
     * @param temperature 随机度
     * @return Ai生成的结果
     */
    public String doRequest(String promptStr, String userStr, Float temperature){
        ArrayList<Message> messages = new ArrayList<>();
        messages.add(new ChatMessage("USER",promptStr));
        messages.add(new ChatMessage("USER",userStr));
        return doRequest(messages, temperature);
    }

    /**
     * 随机度高的回答
     * @param promptStr 提示语
     * @param userStr 生成语
     * @return Ai生成的结果
     */
    public String doUnstableRequest(String promptStr, String userStr){
        return doRequest(promptStr,userStr,UNSTABLE_TEMPERATURE);
    }

    /**
     * 随机度低的回答
     * @param promptStr 提示语
     * @param userStr 生成语
     * @return Ai生成的结果
     */
    public String doStableRequest(String promptStr, String userStr){
        return doRequest(promptStr,userStr,STABLE_TEMPERATURE);
    }
}
